package com.devunion.bogdan.model;

import com.devunion.bogdan.model.project.User;
import com.devunion.bogdan.model.event.UserListener;
import com.devunion.bogdan.model.event.UserEvent;

import javax.swing.event.EventListenerList;

/**
 * @author Viktar Liaskovich (devunion@gmail.com)
 */
public class UserManager {
    private static UserManager ourInstance = new UserManager();

    private EventListenerList listenerList;

    private User user;

    public static UserManager getInstance() {
        return ourInstance;
    }

    private UserManager() {
        listenerList = new EventListenerList();
    }

    public void addUserListener(UserListener listener) {
        listenerList.add(UserListener.class, listener);
    }

    public void removeUserListener(UserListener listener) {
        listenerList.remove(UserListener.class, listener);
    }

    public void setUser(User user) {
        this.user = user;

        fireUserLoggedInEvent(new UserEvent(this, user));
    }

    public User getUser() {
        return user;
    }

    void fireUserLoggedInEvent(UserEvent e) {
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();

        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length - 1; i >= 0; i--) {
            if (listeners[i] == UserListener.class) {
                ((UserListener) listeners[i + 1]).userLoggedIn(e);
            }
        }
    }

}
